package com.yun.util.yun.utils.file;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpATTRS;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.CompressorOutputStream;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.env.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @description: 文件工具类
 */
public class FileNapsUtils {


    public static String createCollectFile(Environment environment, String neName, String taskId, String readIndex, String fileSuffix) throws Exception {
        String collectFileDir = environment.getProperty("collectFile");
        String provinceId = environment.getProperty("ncms.localSystemID");
        String fileName = taskId + "_" + provinceId + "_" + neName + "_" + readIndex + "_" + getCurrentTime("yyyyMMddHHmmss") + "." + (StringUtils.isNotBlank(fileSuffix) ? fileSuffix : "txt");
        File dir = new File(collectFileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String realPath = dir.getAbsolutePath().replace("\\", "/");
        collectFileDir = collectFileDir.replace("\\", "/");
        String prefix = collectFileDir.substring(0, 1);
        if (!realPath.startsWith(prefix)) {
            throw new RuntimeException("[odm-server]所在的服务器不存在UCMP配置项[collectFile]配置的目录");
        }

        dir = new File(dir, "COLLECT");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String dateDir = getCurrentTime("yyyy-MM-dd");

        dir = new File(dir, dateDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return getFileFullPath(dir.getAbsolutePath(), fileName);
    }

    /**
     * 功能描述:
     * 创建上报压缩包的全路径
     * @param zipFilePrefix 压缩包前缀 TaskID_ProvinceID_ DeviceName
     * @return:
     * @exception:
     * @author: DangTing
     * @date: 2019/7/1 17:30
     */
    public static String createZipFile(Environment environment, String zipFilePrefix) {
        String zipDir = environment.getProperty("collect.report.dir");
        File dir = new File(zipDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String realPath = dir.getAbsolutePath().replace("\\", "/");
        zipDir = zipDir.replace("\\", "/");
        String prefix = zipDir.substring(0, 1);
        if (!realPath.startsWith(prefix)) {
            throw new RuntimeException("[odm-server]所在的服务器不存在UCMP配置项[collect.report.dir]配置的目录");
        }

        String dateDir = getCurrentTime("yyyy-MM-dd");
        dir = new File(dir, dateDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return getFileFullPath(dir.getAbsolutePath(), zipFilePrefix + "_" + getCurrentTime("yyyyMMddHHmmss") + ".tar.gz");
    }

    public static String getFileSize(String filePath) {
        String size = "";
        try {
            File file = new File(filePath);
            if (file.exists() && file.isFile()) {
                long fileS = file.length();
                DecimalFormat df = new DecimalFormat("#.00");
                if (fileS < 1024) {
                    size = df.format((double) fileS) + "BT";
                } else if (fileS < 1048576) {
                    size = df.format((double) fileS / 1024) + "KB";
                } else if (fileS < 1073741824) {
                    size = df.format((double) fileS / 1048576) + "MB";
                } else {
                    size = df.format((double) fileS / 1073741824) + "GB";
                }
            } else if (file.exists() && file.isDirectory()) {
               /* logger.error("文件[{}]是文件夹", filePath);*/
                size = "";
            } else {
                /*logger.error("文件[{}]不存在", filePath);*/
                size = "";
            }
        } catch (Exception e) {
            size = "";
           /* logger.error("读取文件大小异常:", e);*/
        }
        return size;
    }

    private static String getCurrentTime(String formatPattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);
        return sdf.format(new Date());
    }

    private static String getFileFullPath(String dir, String fileName) {
        File targetFile = new File(dir, fileName);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
            } catch (IOException e) {
               /* logger.error("创建文件异常:", e);*/
                throw new RuntimeException("创建文件[" + fileName + "]异常:" + e.getMessage());
            }
        }
        String path = targetFile.getAbsolutePath().replace("\\", "/");
        return path;
    }

    /**
     * 压缩文件成Gzip格式，Linux上可使用
     * 压缩文件夹生成后缀名为".gz"的文件并下载
     * @param logFiles        文件列表
     * @param targzipFilePath 压缩文件全路径
     **/
    public static void compressFile(List<File> logFiles, String targzipFilePath) {
        try {
            File outputFile = new File(targzipFilePath);
            FileOutputStream fileOutputStream = FileUtils.openOutputStream(outputFile);
            CompressorOutputStream gzippedOut = new CompressorStreamFactory().createCompressorOutputStream(CompressorStreamFactory.GZIP, fileOutputStream);
            TarArchiveOutputStream taos = new TarArchiveOutputStream(gzippedOut);
            for (File file : logFiles) {
                TarArchiveEntry tae = new TarArchiveEntry(file, file.getName());
                taos.putArchiveEntry(tae);
                taos.write(FileUtils.readFileToByteArray(file));
                taos.closeArchiveEntry();
            }
            taos.close();
            gzippedOut.close();
        } catch (Exception e) {
           /* logger.error("压缩文件异常:", e);*/
        }
    }

    /**
     * 拷贝文件
     * @param sourceFileFullPath
     * @param targetFileFullPath
     * @throws Exception
     */
    public static void fileCopy(String sourceFileFullPath, String targetFileFullPath) throws Exception {
        FileUtils.copyFile(new File(sourceFileFullPath), new File(targetFileFullPath));
    }

    public static boolean isDirExist(String directory, ChannelSftp sftp) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().contains("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }
}
